package com.farm.wdas.client;

import java.io.File;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.farm.wdas.client.domain.FileResource;
import com.farm.wdas.client.domain.Fileinfo;
import com.farm.wdas.client.exception.WdasRemoteException;

/**
 * wdas文件接口(只处理文件客户服务)
 * 
 * @author macpl
 *
 */
public class WSFClient {
	private String operatorPassword;
	private String operatorLoginname;
	private String secret;
	private String baseUrl;
	private String guestKey;
	@SuppressWarnings("unused")
	private static final Logger log = Logger.getLogger(WSFClient.class);

	/**
	 * @param operatorLoginname
	 * @param operatorPassword
	 * @param secret
	 * @param serviceUrl
	 * @param guestkey
	 * @return
	 */
	public static WSFClient getInstance(String operatorLoginname, String operatorPassword, String secret,
			String serviceUrl, String guestkey) {
		WSFClient obj = new WSFClient();
		obj.operatorPassword = operatorPassword;
		obj.operatorLoginname = operatorLoginname;
		obj.secret = secret;
		obj.baseUrl = serviceUrl;
		obj.guestKey = guestkey;
		return obj;
	}

	/**
	 * 上传一个文件到远程WDAP
	 * 
	 * @param file
	 * @param filename
	 * @param fileAppId
	 * @param fileUpdataProcessKey
	 * @param handle
	 * @throws IOException
	 */
	public void uploadFile(File file, String filename, String fileAppId, String fileUpdataProcessKey,
			WSFileHttpUploads.ProgressHandle handle) throws IOException {
		Map<String, String> data = new HashMap<String, String>();
		data.put("fileAppId", fileAppId);
		data.put("filename", filename);
		data.put("processkey", fileUpdataProcessKey);
		data.put("operatorLoginname", operatorLoginname);
		data.put("operatorPassword", operatorPassword);
		data.put("secret", secret);
		data.put("guestkey", guestKey);
		WSFileHttpUploads uploader = WSFileHttpUploads.getInstance(baseUrl.trim() + "/fileapi/file/upload.do", data);
		uploader.setRemoteProgressUrl(baseUrl.trim() + "/fileapi/file/process.do");
		uploader.setProgressHandle(handle);
		uploader.doUpload(file, filename);
	}

	/**
	 * 邏輯刪除文件
	 * 
	 * @param fileId
	 * @throws RemoteException
	 * @throws JSONException
	 */
	public void delFile(String fileAppId) throws WdasRemoteException, JSONException {
		Map<String, String> data = new HashMap<String, String>();
		data.put("fileAppId", fileAppId);
		data.put("operatorLoginname", operatorLoginname);
		data.put("operatorPassword", operatorPassword);
		data.put("secret", secret);
		data.put("guestkey", guestKey);
		JSONObject obj = WSHttpUtils.httpPost(baseUrl.trim() + "/fileapi/file/del.do", data);
		validResult(obj);
	}

	/**
	 * 获得文件状态
	 * 
	 * @param fileId
	 * @throws RemoteException
	 * @throws JSONException
	 */
	public Fileinfo getFileInfo(String fileAppId) throws WdasRemoteException, JSONException {
		Map<String, String> data = new HashMap<String, String>();
		data.put("fileAppId", fileAppId);
		data.put("operatorLoginname", operatorLoginname);
		data.put("operatorPassword", operatorPassword);
		data.put("secret", secret);
		data.put("guestkey", guestKey);
		JSONObject obj = WSHttpUtils.httpPost(baseUrl.trim() + "/fileapi/file/info.do", data);
		validResult(obj);
		if (!obj.isNull("DATA")) {
			JSONObject node = obj.getJSONObject("DATA");
			if (node != null && node.has("id")) {
				Fileinfo info = new Fileinfo();
				info.setCtime(node.getString("ctime"));
				info.setExname(node.getString("exname"));
				info.setFilekey(node.getString("filekey"));
				info.setFilename(node.getString("filename"));
				info.setFilesize(node.getLong("filesize"));
				info.setId(node.getString("id"));
				info.setTitle(node.getString("title"));
				info.setPstate(node.getString("pstate"));
				return info;
			}
		}
		return null;
	}

	/**
	 * 接口状态校验
	 * 
	 * @param fileId
	 * @throws RemoteException
	 * @throws JSONException
	 */
	public void isAble() throws WdasRemoteException, JSONException {
		Map<String, String> data = new HashMap<String, String>();
		data.put("operatorLoginname", operatorLoginname);
		data.put("operatorPassword", operatorPassword);
		data.put("secret", secret);
		data.put("guestkey", guestKey);
		JSONObject obj = WSHttpUtils.httpPost(baseUrl.trim() + "/fileapi/able.do", data);
		validResult(obj);
	}

	/**
	 * 獲得远程文件资源
	 * 
	 * @param fileAppId
	 * @param resourcetype 选填:1文件下载,2文件播放,3在线预览,4txt文本描述,0信息展示,9本地资源
	 * @param tasktype     选填:1持久,0临时
	 * @return
	 * @throws WdasRemoteException
	 * @throws JSONException
	 */
	public List<FileResource> getResources(String fileAppId, String resourcetype, String tasktype)
			throws WdasRemoteException, JSONException {
		Map<String, String> data = new HashMap<String, String>();
		data.put("fileAppId", fileAppId);
		data.put("resourcetype", resourcetype);
		data.put("tasktype", tasktype);
		data.put("operatorLoginname", operatorLoginname);
		data.put("operatorPassword", operatorPassword);
		data.put("secret", secret);
		data.put("guestkey", guestKey);
		JSONObject obj = WSHttpUtils.httpPost(baseUrl.trim() + "/fileapi/file/resources.do", data);
		validResult(obj);
		JSONArray taskJsons = obj.getJSONArray("DATA");
		List<FileResource> resources = new ArrayList<FileResource>();
		for (int n = 0; n < taskJsons.length(); n++) {
			FileResource resource = new FileResource();
			JSONObject node = taskJsons.getJSONObject(n);
			resource.setResourceid(getJsonString(node, "id"));
			resource.setResourceType(getJsonString(node, "type"));
			resource.setState(getJsonString(node, "state"));
			resource.setTaskType(getJsonString(node, "tasktype"));
			resources.add(resource);
		}
		return resources;
	}

	/**
	 * 获得下載地址
	 * 
	 * @param id
	 * @return
	 * @throws JSONException
	 * @throws RemoteException
	 */
	public String getFileDownloadUrl(String fileAppId) throws WdasRemoteException, JSONException {
		Map<String, String> data = new HashMap<String, String>();
		data.put("fileAppId", fileAppId);
		data.put("operatorLoginname", operatorLoginname);
		data.put("operatorPassword", operatorPassword);
		data.put("secret", secret);
		data.put("guestkey", guestKey);
		JSONObject obj = WSHttpUtils.httpPost(baseUrl.trim() + "/fileapi/url/download.do", data);
		validResult(obj);
		if (obj.isNull("url")) {
			return null;
		} else {
			return obj.get("url").toString();
		}
	}

	/**
	 * 获得转换日志地址
	 * 
	 * @param id
	 * @return
	 * @throws JSONException
	 * @throws RemoteException
	 */
	public String getConvetLogUrl(String fileAppId) throws WdasRemoteException, JSONException {
		Map<String, String> data = new HashMap<String, String>();
		data.put("fileAppId", fileAppId);
		data.put("operatorLoginname", operatorLoginname);
		data.put("operatorPassword", operatorPassword);
		data.put("secret", secret);
		data.put("guestkey", guestKey);
		JSONObject obj = WSHttpUtils.httpPost(baseUrl.trim() + "/fileapi/url/convetlog.do", data);
		validResult(obj);
		if (obj.isNull("url")) {
			return null;
		} else {
			return obj.get("url").toString();
		}
	}

	/**
	 * 获得下載地址
	 * 
	 * @param id
	 * @return
	 * @throws JSONException
	 * @throws RemoteException
	 */
	public String getFileViewUrl(String fileAppId) throws WdasRemoteException, JSONException {
		Map<String, String> data = new HashMap<String, String>();
		data.put("fileAppId", fileAppId);
		data.put("operatorLoginname", operatorLoginname);
		data.put("operatorPassword", operatorPassword);
		data.put("secret", secret);
		data.put("guestkey", guestKey);
		JSONObject obj = WSHttpUtils.httpPost(baseUrl.trim() + "/fileapi/url/view.do", data);
		validResult(obj);
		if (obj.isNull("url")) {
			return null;
		} else {
			return obj.get("url").toString();
		}
	}

	/**
	 * 获得播放地址
	 * 
	 * @param id
	 * @return
	 * @throws JSONException
	 * @throws RemoteException
	 */
	public String getFilePlayUrl(String fileAppId) throws WdasRemoteException, JSONException {
		Map<String, String> data = new HashMap<String, String>();
		data.put("fileAppId", fileAppId);
		data.put("operatorLoginname", operatorLoginname);
		data.put("operatorPassword", operatorPassword);
		data.put("secret", secret);
		data.put("guestkey", guestKey);
		JSONObject obj = WSHttpUtils.httpPost(baseUrl.trim() + "/fileapi/url/mediaplay.do", data);
		validResult(obj);
		if (obj.isNull("url")) {
			return null;
		} else {
			return obj.get("url").toString();
		}
	}

	private void validResult(JSONObject obj) throws WdasRemoteException, JSONException {
		if (obj.get("STATE").toString().equals("1")) {
			throw new WdasRemoteException(obj.get("MESSAGE").toString());
		}
	}

	public int getUoloadProcess(String processkey) throws WdasRemoteException, JSONException {
		Map<String, String> data = new HashMap<String, String>();
		data.put("processkey", processkey);
		JSONObject obj = WSHttpUtils.httpPost(baseUrl.trim() + "/fileapi/file/process.do", data);
		validResult(obj);
		return (Integer) obj.get("PROCESS");
	}

	public void submitFile(String fileAppId) throws WdasRemoteException, JSONException {
		Map<String, String> data = new HashMap<String, String>();
		data.put("fileAppId", fileAppId);
		data.put("operatorLoginname", operatorLoginname);
		data.put("operatorPassword", operatorPassword);
		data.put("secret", secret);
		data.put("guestkey", guestKey);
		JSONObject obj = WSHttpUtils.httpPost(baseUrl.trim() + "/fileapi/file/submit.do", data);
		validResult(obj);
	}

	private String getJsonString(JSONObject obj, String path) {
		String[] keys = path.split("\\|");
		JSONObject cobj = obj;
		if (keys.length > 1) {
			for (int n = 0; n <= keys.length - 2; n++) {
				if (cobj.isNull(keys[n])) {
					return null;
				} else {
					cobj = cobj.getJSONObject(keys[n]);
				}
			}
		}
		if (!cobj.isNull(keys[keys.length - 1])) {
			return cobj.getString(keys[keys.length - 1]);
		} else {
			return null;
		}
	}

	@SuppressWarnings("unused")
	private int getJsonInt(JSONObject obj, String path) {
		String[] keys = path.split("\\|");
		JSONObject cobj = obj;
		if (keys.length > 1) {
			for (int n = 0; n <= keys.length - 2; n++) {
				if (cobj.isNull(keys[n])) {
					return 0;
				} else {
					cobj = cobj.getJSONObject(keys[n]);
				}
			}
		}
		if (!cobj.isNull(keys[keys.length - 1])) {
			return cobj.getInt(keys[keys.length - 1]);
		} else {
			return 0;
		}
	}

	/**
	 * 获得文本信息加载地址
	 * 
	 * @param fileAppId
	 * @return
	 * @throws WdasRemoteException
	 * @throws JSONException
	 */
	public String getFileTextUrl(String fileAppId) throws WdasRemoteException, JSONException {
		Map<String, String> data = new HashMap<String, String>();
		data.put("fileAppId", fileAppId);
		data.put("operatorLoginname", operatorLoginname);
		data.put("operatorPassword", operatorPassword);
		data.put("secret", secret);
		data.put("guestkey", guestKey);
		JSONObject obj = WSHttpUtils.httpPost(baseUrl.trim() + "/fileapi/url/text.do", data);
		validResult(obj);
		if (obj.isNull("url")) {
			return null;
		} else {
			return obj.get("url").toString();
		}
	}

	/**
	 * 获得图片加载地址
	 * 
	 * @param fileAppId
	 * @return
	 * @throws WdasRemoteException
	 * @throws JSONException
	 */
	public String getFileImgUrl(String fileAppId, String width) throws WdasRemoteException, JSONException {
		Map<String, String> data = new HashMap<String, String>();
		data.put("fileAppId", fileAppId);
		data.put("width", width);
		data.put("operatorLoginname", operatorLoginname);
		data.put("operatorPassword", operatorPassword);
		data.put("secret", secret);
		data.put("guestkey", guestKey);
		JSONObject obj = WSHttpUtils.httpPost(baseUrl.trim() + "/fileapi/url/img.do", data);
		validResult(obj);
		if (obj.isNull("url")) {
			return null;
		} else {
			return obj.get("url").toString().replace("[width]", width);
		}
	}

	public boolean isAllLoadTaskComplete(String fileAppId) throws JSONException, WdasRemoteException {
		Map<String, String> data = new HashMap<String, String>();
		data.put("fileAppId", fileAppId);
		data.put("operatorLoginname", operatorLoginname);
		data.put("operatorPassword", operatorPassword);
		data.put("secret", secret);
		data.put("guestkey", guestKey);
		JSONObject obj = WSHttpUtils.httpPost(baseUrl.trim() + "/fileapi/file/isAllLoad.do", data);
		validResult(obj);
		if (obj.getBoolean("DATA")) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 获得文件文本
	 * 
	 * @param fileid
	 * @return
	 * @throws WdasRemoteException
	 * @throws JSONException
	 */
	public String getFileText(String fileAppId) throws JSONException, WdasRemoteException {
		String url = getFileTextUrl(fileAppId);
		JSONObject obj = WSHttpUtils.httpGet(url);
		Object text = obj.get("text");
		if (text != null) {
			return text.toString();
		}
		return null;
	}

	public String getToken(String fileAppId) throws JSONException, WdasRemoteException {
		Map<String, String> data = new HashMap<String, String>();
		data.put("fileAppId", fileAppId);
		data.put("guestkey", guestKey);
		data.put("operatorLoginname", operatorLoginname);
		data.put("operatorPassword", operatorPassword);
		data.put("secret", secret);
		JSONObject obj = WSHttpUtils.httpPost(baseUrl.trim() + "/fileapi/regist/token.do", data);
		validResult(obj);
		return obj.getString("TOKEN");
	}

	public boolean isSupport(String exName, Long filesize) {
		Map<String, String> data = new HashMap<String, String>();
		data.put("exname", exName);
		data.put("guestkey", guestKey);
		data.put("filesize", filesize.toString());
		data.put("operatorLoginname", operatorLoginname);
		data.put("operatorPassword", operatorPassword);
		data.put("secret", secret);
		JSONObject obj = WSHttpUtils.httpPost(baseUrl.trim() + "/fileapi/file/support.do", data);
		try {
			validResult(obj);
		} catch (WdasRemoteException e) {
			return false;
		}
		return true;
	}
}
